package com.boby.homecamera.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import com.boby.homecamera.R
import com.google.android.material.tabs.TabLayout
import kotlin.div
import androidx.core.graphics.toColorInt
import com.boby.lib_common.util.BLog

@SuppressLint("ClickableViewAccessibility")
class TabHorizontalScrollView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {
    private lateinit var tabLayout: TabLayout
    private lateinit var scrollView: HorizontalScrollView
    private lateinit var pageContainer: LinearLayout
    private  var pageViews: MutableList<View> = mutableListOf()
    private var isTouching = false
    private var onTabSelectedListener: ((index:Int)-> Unit)? =null

    init {
        LayoutInflater.from(context).inflate(R.layout.view_tab_horizontalscrol,this,true)
        orientation = LinearLayout.VERTICAL
        tabLayout = rootView.findViewById(R.id.tabLayout)
        scrollView = rootView.findViewById(R.id.scrollView)
        pageContainer = rootView.findViewById(R.id.pageContainer)

        // 点击 tab 滚动到对应页面
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val index = tab.position
                val scrollX = index * scrollView.width
                scrollView.smoothScrollTo(scrollX, 0)
                BLog.d("addOnTabSelectedListener","点击 tab 滚动到对应页面: $index")
                onTabSelectedListener?.invoke(index)
            }
            override fun onTabUnselected(tab: TabLayout.Tab) {}
            override fun onTabReselected(tab: TabLayout.Tab) {}
        })

        // 滚动时同步 tab（可选：需添加 Scroll 监听）
        scrollView.viewTreeObserver.addOnScrollChangedListener {
//            if(!isTouching){
//                return@addOnScrollChangedListener
//            }
            val scrollX = scrollView.scrollX
            val pageWidth = scrollView.width
            if (pageWidth == 0) return@addOnScrollChangedListener

            val position = scrollX / pageWidth
            val offsetPx = scrollX % pageWidth
            val offset = offsetPx.toFloat() / pageWidth
//            BLog.d("scroll"," offset: $offset position: $position offsetPx: $offsetPx")
            if (position in 0 until tabLayout.tabCount - 1) {
                tabLayout.setScrollPosition(position, offset, true)
                if(offsetPx == 0 && tabLayout.selectedTabPosition != position){
                    tabLayout.selectTab(tabLayout.getTabAt(position))
                }
            } else if (position == tabLayout.tabCount - 1) {
                // 最后一页确保 offset 为 0，避免越界
                tabLayout.setScrollPosition(position, 0f, true)
                if(offsetPx == 0 && tabLayout.selectedTabPosition != position){
                    tabLayout.selectTab(tabLayout.getTabAt(position))
                }
            }
        }
        scrollView.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> isTouching = true
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    isTouching = false
                    postDelayed({ snapToPage() }, 100) // 延迟处理避免快速滑动卡顿
                }
            }
            false
        }
    }
    fun setOnTabSelectedListener(listener: (index:Int)-> Unit){
        onTabSelectedListener = listener
    }
    fun setData(items : MutableList<Pair<View,String>>){
        // 创建多个页面 View（不要复用）
        pageContainer.removeAllViews()
        pageViews.clear()
        var viewWidth = measuredWidth
        for (item in items) {
            val itemView = item.first
            pageViews.add(itemView)
            itemView.layoutParams = LinearLayout.LayoutParams(
                viewWidth,  // 一屏宽度
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            // 将页面添加到容器
            pageContainer.addView(itemView)
            // 设置 Tab
            tabLayout.setTabTextColors("#333333".toColorInt(),Color.BLACK)
            tabLayout.addTab(tabLayout.newTab().setText(item.second))
        }

        if(viewWidth == 0){
            requestLayout()
        }

    }

    override fun onLayout(
        changed: Boolean,
        l: Int,
        t: Int,
        r: Int,
        b: Int
    ) {
        super.onLayout(changed, l, t, r, b)
        var viewWidth = measuredWidth
        for (itemView in pageViews) {
            val layoutParams = itemView.layoutParams
            layoutParams.width = viewWidth
            itemView.layoutParams = layoutParams
        }
    }

    private fun snapToPage() {
        val pageWidth = scrollView.width
        if (pageWidth == 0) return

        val scrollX = scrollView.scrollX
        val targetPage = (scrollX + pageWidth / 2) / pageWidth
        val scrollToX = targetPage * pageWidth

        scrollView.smoothScrollTo(scrollToX, 0)
        // 同步 TabLayout 状态
//        if (targetPage in 0 until tabLayout.tabCount) {
//            tabLayout.setScrollPosition(targetPage, 0f, true)
//            tabLayout.selectTab(tabLayout.getTabAt(targetPage))
//        }
    }
}